//
//  FQDUserCenterViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/25/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDUserCenterViewController.h"
#import "FQDLabOpinionViewController.h"
#import "FQDLabVoteDetailViewController.h"
#import "FQDSimpleFeedCellItemProvider.h"
#import "FQDAccountManager.h"
#import "FQDRegisterNavViewController.h"
#import "FQDUserCenterRadarCell.h"
#import "FQDQIconEmptyCell.h"
#import "FQDTabBarCell.h"
#import "FQDLabFeedCellItem.h"
#import "FQDRestModel.h"

#import "UICollectionView+XYIndexPathSizeCache.h"

@interface FQDUserCenterViewController () <FQDTabBarCellDelegate>

@property (nonatomic, strong) FQDSimpleFeedCellItemProvider *praiseArticlesProvider;
@property (nonatomic, strong) FQDSimpleFeedCellItemProvider *joinedLabProvider;
@property (nonatomic, assign) NSInteger tabIndex;
@property (nonatomic, strong) FQDTabBarCell *floatTabBarCell;
@property (nonatomic, weak) FQDTabBarCell *tabBarCellInCollectionView;

@end

@implementation FQDUserCenterViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [self setupDefaults];
    [self setupProviders];
    [self setupNotifications];
    
    [super viewDidLoad];
    
}

- (void)setupDefaults
{
    self.tabIndex = 0;
    self.disableRefreshHeader = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self updateNavTitle];
}

- (void)setupProviders
{
    self.praiseArticlesProvider = [[FQDSimpleFeedCellItemProvider alloc] init];
    [self.praiseArticlesProvider setFetchFeedBlock:^(NSString *feedId, NSString *cursorKey, QDailyAPICompleteBlock completion) {
        [[QDailyAPI sharedAPI] getUserPraisedArticleList:cursorKey completion:completion];
    }];
    
    self.joinedLabProvider = [[FQDSimpleFeedCellItemProvider alloc] init];
    [self.joinedLabProvider setFetchFeedBlock:^(NSString *feedId, NSString *cursorKey, QDailyAPICompleteBlock completion) {
        [[QDailyAPI sharedAPI] getUserJoinedLabResearchList:cursorKey completion:completion];
    }];
    self.provider = self.praiseArticlesProvider;
}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(userRadarDidChange:)
                          name:FQDUserRadarDidChangeNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(userAccountDidChange:)
                          name:FQDAccountUserInfoDidChangeNotification object:nil];
}

- (void)updateNavTitle
{
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    if ([accountManager isLogined]) {
        FQDUser *user = accountManager.currentUser;
        self.navView.titleLabel.text = user.username;
    } else {
        self.navView.titleLabel.text = @"";
    }
}

- (void)presentLoginView
{
    FQDRegisterNavViewController *navController = [[FQDRegisterNavViewController alloc] init];
    navController.backgroundViewController = self;
    [self presentViewController:navController animated:YES completion:nil];
}

- (BOOL)shouldShowEmpty
{
    BOOL hasFeeds = [self.provider.cellItems count] > 0;
    BOOL hasMoreCellItems = [self.provider hasMoreCellItems];
    return !hasFeeds && !hasMoreCellItems;
}

- (FQDTabBarCell *)floatTabBarCell
{
    if (!_floatTabBarCell) {
        CGRect feedContentRect = self.feedContentView.frame;
        _floatTabBarCell = [[FQDTabBarCell alloc] init];
        _floatTabBarCell.tabTitles = @[@"喜欢的文章", @"参与的研究"];
        _floatTabBarCell.delegate = self;
        _floatTabBarCell.frame = CGRectMake(0, feedContentRect.origin.y, feedContentRect.size.width, 50.0f);
        _floatTabBarCell.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _floatTabBarCell.hidden = YES;
        [self.view addSubview:_floatTabBarCell];
    }
    _floatTabBarCell.selectedIndex = self.tabIndex;
    return _floatTabBarCell;
}

#pragma Notifications
- (void)userRadarDidChange:(NSNotification *)note
{
    [self reloadData];
}

- (void)userAccountDidChange:(NSNotification *)note
{
    [self updateNavTitle];
    [self loadNewCellItemsWithCompletion:nil];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.tabBarCellInCollectionView) {
        CGFloat tabBarCellY = self.tabBarCellInCollectionView.frame.origin.y;
        if (scrollView.contentOffset.y > tabBarCellY) {
            self.floatTabBarCell.hidden = NO;
        } else {
            self.floatTabBarCell.hidden = YES;
        }
    }
}

#pragma mark - FQDBaseCellActionDelegate
- (void)collectionViewCell:(UICollectionViewCell *)cell actionType:(NSInteger)actionType actionControl:(UIControl *)control userInfo:(NSDictionary *)userInfo
{
    if ([cell isKindOfClass:[FQDUserCenterRadarCell class]]) {
        if (actionType == FQDUserCenterRadarCellActionLogin) {
            [self presentLoginView];
        } else if (actionType == FQDUserCenterRadarCellActionTouchCaption) {
            FQDRadarItem *radarItem = userInfo[FQDUserCenterRadarCellActionTouchCaptionRadarItemInfoKey];
            NSString *radarId = radarItem.ID;
            FQDSimpleFeedCellItemProvider *provider = [[FQDSimpleFeedCellItemProvider alloc] init];
            provider.feedId = radarId;
            [provider setFetchFeedBlock:^(NSString *feedId, NSString *cursorKey, QDailyAPICompleteBlock completion) {
                [[QDailyAPI sharedAPI] getUserRadarArticleList:feedId key:cursorKey completion:completion];
            }];
            
            FQDArticleFeedBaseViewController *afbVC = [[FQDArticleFeedBaseViewController alloc] init];
            afbVC.provider = provider;
            afbVC.title = radarItem.title;
            [self.navigationController pushViewController:afbVC animated:YES];
        }
    }
}

#pragma mark - FQDTabBarCellDelegate
- (void)didSelectTabButton:(UIButton *)button atTabIndex:(NSInteger)tabIndex preTabIndex:(NSInteger)preTabIndex title:(NSString *)title
{
    if (tabIndex != preTabIndex) {
        self.tabIndex = tabIndex;
        self.provider = (tabIndex == 0) ? self.praiseArticlesProvider : self.joinedLabProvider;
        [self.feedCollectionView xy_clearIndexPathSizeCache];
        [self reloadData];
    }
}

#pragma mark - FQDFeedBaseViewController override
- (NSInteger)numberOfHeaderCellsInCollectionView:(UICollectionView *)collectionView
{
    NSInteger headerCount = ([self shouldShowEmpty]) ? 3 : 2;
    return headerCount;
}

- (NSArray *)cellClasses
{
    NSArray *superCellClasses = [super cellClasses];
    return [superCellClasses arrayByAddingObjectsFromArray:@[
                [FQDUserCenterRadarCell class],
                [FQDQIconEmptyCell class],
                [FQDTabBarCell class],
            ]];
}

- (Class)headerCellClassAtIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    if (indexPath.section == 0) {
        return [FQDUserCenterRadarCell class];
    } else if (indexPath.section == 1) {
        return [FQDTabBarCell class];
    } else if (indexPath.section == 2) {
        return [FQDQIconEmptyCell class];
    }
    return nil;
}

- (void)configureHeaderCell:(UICollectionViewCell *)headerCell atIndexPath:(NSIndexPath *)indexPath inCollectionView:(UICollectionView *)collectionView
{
    if (indexPath.section == 0) {
        FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
        FQDUserCenterRadarCell *radarCell = (FQDUserCenterRadarCell *)headerCell;
        radarCell.delegate = self;
        radarCell.radarItems = accountManager.radarItems;
    } else if (indexPath.section == 1) {
        FQDTabBarCell *tabBarCell = (FQDTabBarCell *)headerCell;
        tabBarCell.tabTitles = @[@"喜欢的文章", @"参与的研究"];
        tabBarCell.delegate = self;
        tabBarCell.selectedIndex = self.tabIndex;
        self.tabBarCellInCollectionView = tabBarCell;
    } else if (indexPath.section == 2) {
        if ([self shouldShowEmpty]) {
            FQDQIconEmptyCell *emptyCell = (FQDQIconEmptyCell *)headerCell;
            if (self.provider == self.praiseArticlesProvider) {
                emptyCell.titleText = @"喜欢的文章会出现在这里";
            } else if (self.provider == self.joinedLabProvider) {
                emptyCell.titleText = @"参与的研究会出现在这里";
            }
        }
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForHeaderCellAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size = CGSizeZero;
    if (indexPath.section == 0) {
        size = CGSizeMake(collectionView.frame.size.width, 290.0f);
    } else if (indexPath.section == 1) {
        size = CGSizeMake(collectionView.frame.size.width, 50.0f);
    } else if (indexPath.section == 2) {
        if ([self shouldShowEmpty]) {
            size = CGSizeMake(collectionView.frame.size.width, 227.0f);
        }
    }
    return size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetsForHeaderCellSection:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 5, 0);
}

@end
